package com.la.yuer.prc.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 创建连接
        ServerSocket serverSocket = new ServerSocket(9999);
        while(true){
            final Socket socket = serverSocket.accept();
            executorService.execute(new Runnable() {
                public void run() {
                        handlerMassage(socket);
                }
            });
        }
    }

    private static void handlerMassage(Socket socket){
        System.out.println("线程的ID： " +Thread.currentThread().getId()+"   线程的名称： "+Thread.currentThread().getName());
        // 从输入流中读取消息，
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            byte [] bt = new  byte[1024];
            int readLength = inputStream.read(bt);
            System.out.println("客户端："+ new String(bt,0,readLength));
            OutputStream os = socket.getOutputStream();
            os.write("对不起，我没钱了".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
